<?php

namespace app\admin\controller;

use addons\epay\library\Service;
use app\admin\model\commission\Log;
use app\admin\model\order\Operations;
use app\api\service\OrderService;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;
    protected $searchFields = 'order_no,goodname,user.nickname';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        $this->view->assign("orderTypeList", $this->model->getOrderTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '', 'trim'), true);
            $order_type = isset($filter['order_type']) ? $filter['order_type'] : null;
            // 如果存在 realname，进行相关处理
            if (isset($filter['order_type'])) {
                unset($filter['order_type'], $op['order_type']);
            }
            $this->request->get(['filter' => json_encode($filter, true)]);
            $this->request->get(['op' => json_encode($op, true)]);


            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            $query = $this->model
                ->with(['user', 'rider'])
                ->where($where);
            if ($order_type === 'child' || $order_type === 'senior') {
                $query->where('order_type', '=', $order_type)
                    ->where('goodtype', '=', 0);
            } else if ($order_type === 'RIDER') {
                $query->where('goodtype', '=', 1);
            }
            $list = $query->order($sort, $order)->paginate($limit);
            foreach ($list as $row) {
                if($row->goodtype==1){
                    $row->order_type='RIDER';
                }
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function zhipai($id,$riderid){
        $order=\app\admin\model\Order::where('id','=',$id)->find();
        if($order['order_status']!=1){
            $this->error('该订单无法操作');
        }
        if($order['riderid']!=null) {
            $this->error('已分配陪伴师');
        }
        $result=\app\admin\model\Order::where('id','=',$id)->update(['riderid'=>$riderid,'receiv_time'=>time()]);
        if($result){
            $OrderService=new OrderService();
            $OrderService->fenyong($order['id']);
        }
        $this->success();
    }

    /**
     * 退款
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function refund($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            if($row['order_status']!=1&&$row['is_reach']!=0){
                $this->error('陪伴师已到达,不可退款');
            }
            if($row['refund_status']!=0){
                $this->error('当前订单已退款');
            }
            if($params['refundAmount']<=0){
                $this->error('请输入有效金额');
            }
                //退款
            $order=new Service();
            $orderNo = date('YmdHis') . substr(microtime(), 2, 5) . mt_rand(10000, 99999);
            $result= $order->refund($orderNo, $row['order_no'], $params['refundAmount']*100,$params['refundAmount']*100);
            // 检查退款结果
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                //修改订单状态
                $row->order_status = 3;
                $row->refund_status = 1;
                $row->refund_fee=$params['refundAmount'];
                $row->cancel_role='SYSTEM';
                $row->cancel_reason=$params['refundReason'];
                $row->memo='平台取消订单';
                $row->refund_time=time();
                $row->save();
                //如果有优惠券 退回优惠券
                if ($row['coupon_record_id'] > 0) {
                    \app\admin\model\CouponRecord::where('id', '=', $row['coupon_record_id'])->update(['status' => 0]);
                }
                //删除分佣记录
                Log::where('order_id','=',$row['id'])->where('status','=',0)->delete();
                //订单操作
                Operations::create([
                    'order_id' => $row['id'],
                    'action' => '取消订单',
                    'user_id' => 0,
                    'description' => '平台取消订单',
                    'created_at' => time(),
                    'updated_at' => time(),
                ]);
            } else {
                $this->error( $result['err_code_des']);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }




}
